package com.change.copy.utils;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.change.copy.dto.SparkApiDto;
import com.change.copy.vo.SparkApiVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 讯飞星火 ai 工具类
 */
@Slf4j
@Service
public class SparkAiUtils extends AiUtil {
    @Value("${spark.api}")
    private String sparkApi;

    @Value("${spark.password}")
    private String sparkPassword;

    @Value("${spark.model}")
    private String sparkModel;

    @Value("${spark.stream}")
    private Boolean sparkStream;

    /**
     * 获取讯飞星火的返回内容
     */
    public String getContent(String content) {
        try {
            String url = sparkApi;
            Map<String, String> headers = new HashMap<>(16);
            headers.put("Authorization", sparkPassword);
            SparkApiDto sparkApiDto = SparkApiDto.getDto(content)
                    .setModel(sparkModel)
                    .setStream(sparkStream);
            String body = HttpUtil.createPost(url)
                    .addHeaders(headers)
                    .body(JSON.toJSONString(sparkApiDto))
                    .execute()
                    .body();
            SparkApiVo sparkApiVo = JSONObject.parseObject(body, SparkApiVo.class);
            return sparkApiVo.getContent();
        } catch (HttpException e) {
            log.error("getSparkContent 讯飞星火API报错", e);
            throw e;
        }
    }

}
